var exec = require('child_process').exec;
var http = require('http');
var querystring = require('querystring');
var fs = require('fs');
http.createServer(function (req, res) {
  var arg = req.url.match(/\?([a-zA-Z0-9\&\=\.]*)/);
  console.log(req.url);
  if(arg !== null){
    res.writeHead(200, {'Content-Type': 'text/plain'});
    arg = arg[1];
    arg = querystring.parse(arg, "&", "=");
    exec("g++ ./calculation1.cpp -o ./calculation.lexe", function(error, stdout, stdError){
      if(error || stdError){
	console.log("ErRor!!!");
	res.end(JSON.stringify({ error: (stdError ? stdError : error)}));
      } else {
        exec("./calculation.lexe " + arg.XEnd + " " + arg.Nx + " " + arg.TEnd + " " + arg.NTimes +
        " > ./calculation.json", 
          function(error, stdout, stdError){
            if(error || stdError){
	      console.log(error);
	      res.end(JSON.stringify({ error: (error ? error : stdError)}));
            } else {
	      fs.readFile("./calculation.json", function(error, data){
		res.end(data);
	      });
	    }
          }
        );
      }
    });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    //fs.readFile("./index.html");
    var path = req.url;
    if(req.url === "/"){
      path = "/index.html";
    }
    fs.readFile("." + path, function(error, fileData){
      res.end(fileData);
    });
  }
}).listen(8311, '127.0.0.1');
console.log("Test");
